package com.carful.xigua.modules.common.advice;

import com.alibaba.fastjson.JSON;
import com.carful.xigua.modules.common.annotation.CustomResultBody;
import com.carful.xigua.modules.common.entity.Rest;
import com.carful.xigua.modules.common.entity.RestBody;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.annotation.Annotation;

/**
 * 统一返回体包装器
 *
 * @author felord.cn
 * @since 14:58
 **/
@RestControllerAdvice
public class RestBodyAdvice implements ResponseBodyAdvice<Object> {

    private static final Class<? extends Annotation> ANNOTATION_TYPE = CustomResultBody.class;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        boolean b = !(AnnotatedElementUtils.hasAnnotation(returnType.getContainingClass(), ANNOTATION_TYPE) || returnType.hasMethodAnnotation(ANNOTATION_TYPE));
        return b;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {

        if (o == null) {
            return RestBody.ok();
        }
        if (Boolean.class.isAssignableFrom(o.getClass())) {
            return RestBody.okData(0, (boolean) o ? "成功" : "失败");
        }
        if (Rest.class.isAssignableFrom(o.getClass())) {
            return o;
        }
        if (String.class.isAssignableFrom(o.getClass())) {
            return JSON.toJSONString(RestBody.ok((String) o));
        }
        return RestBody.okData(o);
    }
}
